<template>
  <div class="search">
    <span class="role">顾客姓名：</span>
    <div class="guest">
      <el-input v-model="guestName" placeholder="请输入顾客姓名" size="small" />
    </div>
    <span class="role">结账状态：</span>
    <el-select v-model="resideStateId" class="select-role" size="small">
      <el-option
        v-for="item in resideStateData"
        :key="item.resideStateId"
        :label="item.resideStateName"
        :value="item.resideStateId"
      />
    </el-select>
    <el-button 
      size="small" 
      type="success" 
      @click="searchGuest"
    >查询</el-button>
    <el-button 
      size="small" 
      type="info" 
      @click="toExcel"
    >导出Excel</el-button>
    <el-button 
      size="small" 
      type="primary" 
      @click="openDrawerHandler"
    >添加</el-button>
  </div>
  <el-table size="small" :data="tableData" style="width: 99%">
    <el-table-column prop="guestId" label="编号" width="50" />
    <el-table-column prop="guestName" label="姓名" width="70" />
    <el-table-column prop="identityId" label="身份证" width="150" />
    <el-table-column prop="phone" label="手机号" width="100" />
    <el-table-column prop="roomId" label="房间号" width="70" />
    <el-table-column prop="room.roomType.roomTypeName" label="房间类型" />
    <el-table-column prop="resideDate" label="入住日期" width="150" />
    <el-table-column prop="leaveDate" label="离开日期" width="150" />
    <el-table-column prop="deposit" label="押金" width="70" />
    <el-table-column prop="totalMoney" label="消费金额" width="70" />
    <el-table-column prop="resideState.resideStateName" label="结账状态">
      <template #default="scope">
        <el-tag
          size="small"
          v-if="scope.row.resideState.resideStateId == '2'"
          type="success"
        >
          {{ scope.row.resideState.resideStateName }}
        </el-tag>
        <el-tag
          size="small"
          v-else-if="scope.row.resideState.resideStateId == '1'"
          type="danger"
        >
          {{ scope.row.resideState.resideStateName }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="200">
      <template #default="scope">
        <el-button 
          size="small" 
          type="warning" 
          v-if="scope.row.resideState.resideStateId == '1'"
          @click="handleEdit(scope.row)"
        >编辑</el-button>
        <el-button
          size="small"
          type="danger"
          v-if="scope.row.resideState.resideStateId == '2'"
          @click="handleDelete(scope.row)"
        >删除</el-button>
        <el-button 
          size="small" 
          type="primary" 
          v-if="scope.row.resideState.resideStateId == '1'"
          @click="handleCheckout(scope.row)"
        >结账</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="pages">
    <el-pagination background small layout="prev, pager, next" :total="total" :page-size="pageSize" v-model:current-page="pageIndex" @current-change="curChange" />
  </div>
  <el-drawer
    v-model="openDrawer"
    :title="`${isAdd ? '添加' : '编辑'}顾客`"
    :before-close="handleClose"
    size="30%"
  >
    <div class="item">
      <span>顾客姓名：</span>
      <div>
        <el-input v-model="formData.guestName" placeholder="请输入顾客姓名" size="small" />
      </div>
    </div>
    <div class="item">
      <span>身份证号：</span>
      <div>
        <el-input v-model="formData.identityId" placeholder="请输入身份证号" size="small" />
      </div>
    </div>
	<div class="item">
	  <span>手机号：</span>
	  <div>
	    <el-input v-model="formData.phone" placeholder="请输入手机号" size="small" />
	  </div>
	</div>
	<div class="item">
	  <span>房间类型：</span>
	  <div>
	    <el-select v-model="formData.roomTypeId" class="select-role" size="small" @change="">
	      <el-option
	        v-for="item in roomTypesData"
	        :key="item.roomTypeId"
	        :label="item.roomTypeName"
	        :value="item.roomTypeId"
	      />
	    </el-select>
	  </div>
	</div>
	<div class="item">
	  <span>房间编号：</span>
	  <div>
		<el-select v-model="formData.roomId" class="select-role" size="small">
		  <el-option
		    v-for="item in roomList"
		    :key="item.roomId"
		    :label="item.roomId"
		    :value="item.roomId"
		  />
		</el-select>
	  </div>
	</div>
	<div class="item">
	  <span>入住日期：</span>
	  <div>
      <el-date-picker v-model="formData.resideDate" type="datetime" placeholder="请输入入住日期" size="small"></el-date-picker>
	  </div>
	</div>
	<div class="item">
	  <span>押金：</span>
	  <div>
	    <el-input v-model.number="formData.deposit" placeholder="请输入押金" size="small" />
	  </div>
	</div>
	<div class="item">
	  <span>入住人数：</span>
	  <div>
	    <el-input v-model.number="formData.guestNum" placeholder="请输入入住人数" size="small" />
	  </div>
	</div>
    <div class="item">
      <span></span>
      <div>
        <el-button 
          size="small" 
          type="primary" 
          @click="editGuest"
        >{{isAdd ? '添加' : '编辑'}}</el-button>
        <el-button 
          size="small" 
          @click="clearInput"
        >重置</el-button>
      </div>
    </div>
  </el-drawer>
</template>
<script>
import {reactive, toRefs, watch, nextTick} from 'vue';
import {list, add, update, checkout, del} from '../../api/guest';
import {list as getResideStateList} from '../../api/resideState';
import {getRoomTypeList} from '../../api/roomType';
import {list as getRoomList} from '../../api/room';
import {$confirm, $msg_e} from '../../utils/msg';
import {xlsx} from '../../utils/xlsx';

export default {
  name: 'Guest',
  setup(){
    const state = reactive({
      tableData: [], //顾客列表数据
      guestName: '', //顾客姓名
      resideStateId: 0, //结账编号
      total: 0, //总条目数
      pageIndex: 1, //当前页
      pageSize: 10, //每页显示条数
      resideStateData: [], //结账状态数据
      openDrawer: false, //是否显示 Drawer
      formData: {
        guestId: 0, //顾客编号
        guestName: '', //顾客姓名
        identityId: '', //身份证号
        phone: '', //手机号
        roomTypeId: '0', //房间类型编号
        roomId: '请选择房间编号', //房间编号
        resideDate: '', //入住日期
        deposit: '', //押金
        guestNum: '', //入住人数
      },
      isAdd: true, //是否添加顾客
      roomTypesData: [], //房间类型数据
      roomList: [], //房间类型对应的房间号数据
    });

    //点击删除按钮
    const handleDelete = async (row) => {
      await $confirm('确定删除该顾客吗？');

      const {guestId} = row;
      const result = await del({guestId});

      if(result){
        //成功
        loadTable();
      }
    }

    //点击结账按钮
    const handleCheckout = async (row) => {
      const {guestId, resideDate} = row;

      if(new Date(resideDate) < Date.now()){
        //可以结账
        await checkout({guestId});
        loadTable();
      } else {
        //不可以结账
        $msg_e('未到结账时间');
      }
    }

    //点击编辑按钮
    const handleEdit = (row) => {
      const obj = {}

      for(const key in row){
        if(typeof row[key] === 'object'){
          //值是对象
          for(const secondaryKey in row[key]){
            if(secondaryKey === 'roomType'){
              //房间类型
              obj.roomTypeId = row[key][secondaryKey].roomTypeId + '';
            }
          }
        }else{
          //值不是对象
          obj[key] = row[key];

          if(key === 'roomId'){
            //原房间编号
            obj.id = row[key];
            obj[key] = row[key] + '';
          }

          if(key === 'identityId' || key === 'phone'){
            //身份证号或手机号
            obj[key] = row[key] + '';
          }
        }
      }

      state.formData = obj;

      nextTick(() => {
        state.formData.roomId = row.roomId + '';
      });

      state.isAdd = false;
      state.openDrawer = true;
    }

    //添加、编辑顾客
    const editGuest = async () => {
      let result = false;

      if(state.isAdd){
        //添加
        delete state.formData.id;
        result = await add(state.formData);
      }else{
        //编辑
        result = await update(state.formData);
      }

      if(result){
        //成功
        loadTable();
      }
    }

    //点击重置按钮
    const clearInput = () => {
      state.formData = {
        guestId: 0, //顾客编号
        guestName: '', //顾客姓名
        identityId: '', //身份证号
        phone: '', //手机号
        roomTypeId: '0', //房间类型编号
        roomId: '请选择房间编号', //房间编号
        resideDate: '', //入住日期
        deposit: '', //押金
        guestNum: '', //入住人数
      }
    }

    //关闭抽屉
    const handleClose = () => {
      clearInput();
      state.openDrawer = false;
    }
	
    //加载房间类型数据
    const loadRoomTypes = async () => {
      const data = await getRoomTypeList();
    
      data.unshift({
        roomTypeId: '0',
        roomTypeName: '请选择房间类型',
      });
    
      state.roomTypesData = data;
    }
    
    loadRoomTypes();
    
    //加载房间类型对应的房间号数据
    const loadRoomList = async (roomTypeId) => {
      const {data: roomData} = await getRoomList({
        roomTypeId,
        guestId: state.formData.guestId,
        roomStateId: '1',
        pageSize: 100,
      });

      roomData.unshift({roomId: '请选择房间编号'});
      state.roomList = roomData;
    }

    //加载顾客列表数据
    const loadTable = async () => {
      const params = {
        pageIndex: state.pageIndex,
        pageSize: state.pageSize,
        guestName: state.guestName,
        resideStateId: state.resideStateId,
      }

      const {data: guestData, count, pageIndex, pageSize} = await list(params);

      state.tableData = guestData;
      console.log('state.tableData:');
      console.log(state.tableData);
      state.total = count;
      state.pageSize = pageSize;
      state.pageIndex = pageIndex;
    }

    loadTable();

    //加载结账状态数据-查询
    const loadResideStates = async () => {
      const data = await getResideStateList();

      data.unshift({
        resideStateId: 0,
        resideStateName: '请选择结账状态',
      });

      state.resideStateData = data;
    }

    loadResideStates();

    //current-page 改变时触发
    const curChange = (current) => {
      state.pageIndex = current;
      loadTable();
    }

    //点击查询按钮
    const searchGuest = () => {
      state.pageIndex = 1;
      loadTable();
    }
	
    //打开抽屉
    const openDrawerHandler = () => {
      state.isAdd = true;
      state.openDrawer = true;
    }

    watch(
      () => state.formData.roomTypeId,
      (val) => {
        state.formData.roomId = '请选择房间编号';

        if(val > 0){
          //选择了有效房间类型
          loadRoomList(val);
        }else{
          //未选择有效房间类型
          state.roomList = [];
        }
      }
    );

    //导出 excel
    const toExcel = () => {
      const excelData = state.tableData.map(guest => {
        const {roomId, room, guestId, identityId, guestName, phone, resideDate, leaveDate, deposit, totalMoney, resideState} = guest;

        return {
          guestId,
          identityId,
          guestName,
          phone,
          roomTypeName: room.roomType.roomTypeName,
          roomId,
          resideDate,
          leaveDate,
          deposit,
          totalMoney,
          resideStateName: resideState.resideStateName,
        }
      });

      const excelHeader = {
        guestId: '顾客编号',
        identityId: '身份证',
        guestName: '姓名',
        phone: '手机号',
        roomTypeName: '房间类型',
        roomId: '房间号',
        resideDate: '入住日期',
        leaveDate: '离开日期',
        deposit: '押金',
        totalMoney: '消费金额',
        resideStateName: '结账状态',
      }

      xlsx(excelData, excelHeader, '顾客信息');
    }

    return {
      ...toRefs(state),
      curChange,
      searchGuest,
      openDrawerHandler,
      clearInput,
      handleClose,
      editGuest,
      handleEdit,
      handleCheckout,
      handleDelete,
      toExcel,
    }
  },
}
</script>
<style lang="scss" scoped>
.pages {
  padding-top: 10px;
}
.item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  span {
    width: 70px;
    font-size: 14px;
    text-align: right;
  }
  div {
    flex: 1;
  }
}
.search {
  .guest {
    display: inline-block;
    width: 200px;
    margin-right: 10px;
  }
}
</style>